/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.ui;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.http.HttpConfig;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppConfig;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.ApiHttpClient;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.base.BaseActivity;
import com.talben.soudian.bean.User;
import com.talben.soudian.util.StringUtils;

/**
 * @Title: RegisterAcivity.java
 * @Package com.talben.soudian.ui
 * @Description: 注册。
 * @author Tal.Ben
 * @date 2015年5月24日 下午2:44:46
 * @version v1.0
 */
public class RegisterAcivity extends BaseActivity{

	@InjectView(R.id.et_username)
    EditText mEtUserName;
	
	@InjectView(R.id.et_phone)
	EditText mEtUserPhone;

	@InjectView(R.id.et_email)
	EditText mEtUserEmail;
	
    @InjectView(R.id.et_password)
    EditText mEtPassword;
    
    @InjectView(R.id.et_confirm_password)
    EditText mEtConfirmPassword;
    
    @InjectView(R.id.btn_register)
    Button mBtnRegister;
    
    private String mUserName;
    private String mUserPhone;
    private String mUserEmail;
    private String mPassword;
	
    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }
    
    @Override
    protected boolean hasBackButton() {
        return true;
    }
    
    @Override
    protected int getActionBarTitle() {
        return R.string.register;
    }
    
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
        case R.id.btn_register:
            handleRegister();
            break;
        default:
            break;
        }
	}

	private void handleRegister(){
		 if (!prepareForRegister()) {
	            return;
	        }

        // if the data has ready
        mUserName = mEtUserName.getText().toString();
        mUserPhone = mEtUserPhone.getText().toString();
        mUserEmail = mEtUserEmail.getText().toString();
        mPassword = mEtPassword.getText().toString();

        showWaitDialog(R.string.progress_register);
        SouDianAPI.register(mUserName, mUserPhone, mUserEmail, mPassword, 
        		TDevice.getMacAddress(RegisterAcivity.this), mHandler);
	}
	
	private boolean prepareForRegister() {
        if (!TDevice.isNetworkReady(getApplicationContext())) {
            AppContext.showToastShort(R.string.tip_no_internet);
            return false;
        }
        String uName = mEtUserName.getText().toString();
        if (StringUtils.isEmpty(uName)) {
            AppContext.showToastShort(R.string.tip_please_input_username);
            mEtUserName.requestFocus();
            return false;
        }
        String uPhone = mEtUserPhone.getText().toString();
        if (StringUtils.isEmpty(uPhone)) {
        	AppContext.showToastShort(R.string.tip_please_input_phone);
        	mEtUserPhone.requestFocus();
            return false;
		} else if(!uPhone.matches("[1][358]\\d{9}")){
			AppContext.showToastShort(R.string.tip_illegal_phone);
			mEtUserPhone.setText("");
			mEtUserPhone.requestFocus();
            return false;
		}
        String uEmail = mEtUserEmail.getText().toString();
        if (StringUtils.isEmpty(uEmail)) {
        	AppContext.showToastShort(R.string.tip_please_input_email);
        	mEtUserEmail.requestFocus();
        	return false;
        } else if(!StringUtils.isEmail(uEmail)){
        	AppContext.showToastShort(R.string.tip_illegal_email);
        	mEtUserEmail.setText("");
        	mEtUserEmail.requestFocus();
        	return false;
		}
        String pwd = mEtPassword.getText().toString();
        if (StringUtils.isEmpty(pwd)) {
            AppContext.showToastShort(R.string.tip_please_input_password);
            mEtPassword.requestFocus();
            return false;
        }
        String uCfPwd = mEtConfirmPassword.getText().toString();
        if (StringUtils.isEmpty(uCfPwd)) {
        	AppContext.showToastShort(R.string.tip_please_input_confirm_password);
        	mEtConfirmPassword.requestFocus();
        	return false;
        } else if (!pwd.equals(uCfPwd)) {
        	AppContext.showToastShort(R.string.tip_illegal_confirm_password);
        	mEtConfirmPassword.setText("");
        	mEtConfirmPassword.requestFocus();
        	return false;
		}
        return true;
    }
	
	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideWaitDialog();
			String result;
			//AppContext.showToast(R.string.tip_register_error_for_network);
			try {
				result = new String(arg2,"utf-8");
				JSONObject resJObj = new JSONObject(result);
				AppContext.showToast(resJObj.getString("msg"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				//保存cookie
				AppContext.setCookie(RegisterAcivity.this);
				//处理Json
                String result = new String(arg2,"utf-8");
                JSONObject resJObj = new JSONObject(result);
                User user = new User();
                if (resJObj.getString("result").equals("success")) {
					user.setuPassword(mPassword);
					user.setUname(mUserName);
					user.setuPhone(mUserPhone); 
					user.setuEmail(mUserEmail);
					user.setuScore("0");
					user.setuCoin("0");
					user.setuGiftLog("未获取积分");
					user.setUaccount(user.getuPhone());
					//保存到数据库.
					KJDB db = KJDB.create(RegisterAcivity.this);
					db.save(user);
					
					AppContext.getInstance().saveUserInfo(user);
                    hideWaitDialog();
                    handleRegisterSuccess();
				} else {
					AppContext.getInstance().cleanLoginInfo();
                    hideWaitDialog();
                    AppContext.showToast(resJObj.getString("msg"));
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
	
    private void handleRegisterSuccess() {
		// TODO Auto-generated method stub
		UIHelper.gotoLoginPage(RegisterAcivity.this);
		finish();
	}
    
	@Override
	public void initView() {
		mBtnRegister.setOnClickListener(this);
	}
	
	@Override
	public void initData() {
		
	}

}

